﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;

namespace FrameworkQ.Readable
{
    public class ParagraphStrategy : ITextParserStrategy 
    {
        public int IgnoreWithWordsLessThan { get; set; }

        public bool Parse(HtmlAgilityPack.HtmlDocument document, Parser parser)
        {
            HtmlNodeCollection colParagraphs = document.DocumentNode.SelectNodes(xpath: "//p");

            StringBuilder sbText = new StringBuilder();
            StringBuilder sbHtml = new StringBuilder();

            foreach (HtmlNode paragraph in colParagraphs)
            {
                int wordCount = paragraph.InnerText.Trim().Split(" ".ToCharArray()).Length;
                if (wordCount >= this.IgnoreWithWordsLessThan)
                {
                    sbText.AppendLine(paragraph.InnerText);
                    sbHtml.AppendLine(paragraph.OuterHtml);
                }
            }

            parser.Html = sbHtml.ToString();
            parser.Text = sbText.ToString();

            HtmlNode ndTitle = document.DocumentNode.SelectSingleNode("//title");
            HtmlNode ndH1 = document.DocumentNode.SelectSingleNode("//h1");

            if (ndTitle!=null)
                parser.Title = ndTitle.InnerText;
            else if (ndH1 != null)
                parser.Title = ndH1.InnerText;


            return true;
        }

    }
}
